package com.djj.nanny.controller;

import com.djj.nanny.entity.Menu;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import com.djj.nanny.dto.UserPasswordUpdateDTO;
import com.djj.nanny.common.Result;
import com.djj.nanny.entity.User;
import com.djj.nanny.service.UserService;
import com.djj.nanny.service.MenuService;
import com.djj.nanny.util.JwtTokenUtils;
import com.djj.nanny.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Tag(name = "用户管理接口")
@RestController
@RequestMapping("/user")
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @Resource
    private MenuService menuService;

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<?> register(@RequestBody  User user) {
        LOGGER.info("用户注册: {}", user.getUsername());
        userService.createUser(user);
        return Result.success("注册成功");
    }

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<User> login(@RequestBody Map<String, String> loginForm) {
        String username = loginForm.get("username");
        String password = loginForm.get("password");
        String captcha = loginForm.get("captcha");
        String captchaKey = loginForm.get("captchaKey");

        if (StringUtils.isAnyBlank(username, password, captcha, captchaKey)) {
            throw new ServiceException("请填写完整信息");
        }

        User user = userService.login(username, password, captcha, captchaKey);
        
        // 获取用户的菜单权限
        List<Menu> menus = menuService.getMenusByRoleCode(user.getRoleCode());
        String token = JwtTokenUtils.genToken(String.valueOf(user.getId()), user.getPassword());
        user.setMenuList(menus);
        user.setToken(token);
        
        return Result.success(user);
    }

    @Operation(summary = "更新用户信息")
    @PutMapping("/info")

    public Result<?> updateUserInfo(@RequestBody @Valid User user) {
        LOGGER.info("更新用户信息: {}", user.getId());
        userService.updateUser( user);
        return Result.success("更新成功");
    }

    @Operation(summary = "修改密码")
    @PutMapping("/password/{id}")

    public Result<?> updatePassword(@PathVariable Long id, @RequestBody UserPasswordUpdateDTO dto) {
        LOGGER.info("修改密码");
        userService.updatePassword(id,dto);
        return Result.success("密码修改成功");
    }

    @Operation(summary = "获取用户列表")
    @GetMapping("/list")

    public Result<?> getUserList(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String roleCode,
            @RequestParam(required = false) Integer status) {
        LOGGER.info("获取用户列表: pageNum={}, pageSize={}", pageNum, pageSize);
        return Result.success(userService.getUsersByPage(username, roleCode, status, pageNum, pageSize));
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{id}")

    public Result<?> deleteUser(@PathVariable Long id) {
        LOGGER.info("删除用户: {}", id);
        userService.deleteUserById(id);
        return Result.success("删除成功");
    }

    @Operation(summary = "批量删除用户")
    @DeleteMapping("/batch")
    public Result<?> batchDeleteUsers(@RequestBody List<Long> ids) {
        LOGGER.info("批量删除用户: {}", ids);
        userService.batchDeleteUsers(ids);
        return Result.success("批量删除成功");
    }

    @Operation(summary = "重置用户密码")
    @PutMapping("/{id}/reset-password")
    public Result<?> resetPassword(@PathVariable Long id) {
        LOGGER.info("重置用户密码: {}", id);
      String newPwd=  userService.resetPassword(id);
        return Result.success("密码重置成功,新密码为："+newPwd);
    }

    @Operation(summary = "根据角色查找用户")
    @GetMapping("/role/{roleCode}")
    public Result<?> getUsersByRole(
            @PathVariable String roleCode
           ) {
        LOGGER.info("根据角色查找用户: roleCode={}", roleCode);
        return Result.success(userService.getUsersByPage(null, roleCode, null, 1, Integer.MAX_VALUE));
    }
}
